//
//  AppDelegate.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/5.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "AppDelegate.h"
#import "HMainWC.h"
#import "HCoreConfig.h"
#import "HJAudioPlayer.h"

#import "HSQLManager.h"
#import "HPlaylistItem.h"
#import "HSongItem.h"
#import "HView.h"
#import "HMenuItem.h"

//#import "HlyricsParser.h"


@interface AppDelegate()


@property (nonatomic,strong) NSString * clickFilename;

@end

@implementation AppDelegate


-(id)init {
    
    self=[super init];
    
    if (self) {
        self.clickFilename=nil;
        
    }
    
    return self;
}


-(void)awakeFromNib {



}





- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename{

    debugLog(@"filename:%@",filename);
    
    
    if (filename) {
        self.clickFilename=filename;
    
    if (self.mainWc) {
        
        [self playClickSong];
 
    }
    
    }

    return YES;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    
    
    
    /*测试 自定义document packge
     NSString * desktopDir=[NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) objectAtIndex:0] ;
     
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     
     NSString *documentsDirectory = [paths objectAtIndex:0];
     
     NSURL *dirUrl = [NSURL fileURLWithPath:documentsDirectory];
     
     NSString * thepath=[desktopDir stringByAppendingPathComponent:@"kuk"];
     
     NSImage * img=[NSImage imageNamed:@"icon"];
     NSImage * timg=[NSImage imageNamed:@"ttt"];
     
     
     NSFileWrapper *imageFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:img.TIFFRepresentation];
     [imageFileWrapper setPreferredFilename:@"image"];
     
     NSFileWrapper * wa=[[NSFileWrapper alloc] initDirectoryWithFileWrappers:@{@"img":imageFileWrapper}];
     [wa setPreferredFilename:@"kuk"] ;
     
     NSError * error;
     NSURL * url=[NSURL URLWithString:desktopDir];
     bool issuccess=[wa writeToURL:[dirUrl URLByAppendingPathComponent:@"ktk.hskin"] options:NSFileWrapperWritingAtomic originalContentsURL:nil error:&error];
     
     if (!issuccess) {
     debugLog(@"erroe:%@",error);
     }
     
     */
    
    
    
    
    /* keypath 测试
    
    NSDictionary * wdic=@{ @"version": @{@"version": @"1.0"},
                           @"string":@{@"author":@"HJ",
                                       @"skinName":@"default",
                                       @"skinDes":@"This is the default skin",
                                       @"gengrateDate":@"2014-09-10 13:00:00"
                                       },
                           @"type":@{@"templateType":@"gen_1",
                                     @"categoryType":@"1"},
                           
                           @"color":@{@"titleBarBGColor":@"255,211,36,255",
                                      
                                      @"leftListGroupCellBGColor":@"255,211,36,255",
                                      @"leftListGroupCellTextolor":@"255,211,36,255",
                                      @"leftListNormalCellBGColor":@"255,211,36,255",
                                      @"leftListNormalCellTextColor":@"255,211,36,255",
                                      
                                      @"rightListCellBGColor1":@"255,211,36,255",
                                      @"lrightistCellBGColor2":@"255,211,36,255",
                                      @"rightListCellHighlightBGColor":@"255,211,36,255",
                                      @"rightListCellTextColor":@"255,211,36,255",
                                      @"rightListCellHighlightTextColor":@"255,211,36,255"
                                      },
                           @"font": @{@"font1": @{@"fontName":@"hel",@"fontColor":@"red",@"fontSize":@"15"},
                                      @"font2": @{@"fontName":@"ver",@"fontColor":@"blue",@"fontSize":@"16"}},
                           @"frame":@{@"frame":@""},
                           @"image":@{@"image":@""},
                           @"linewidth":@{@"linewidth":@""},
                           @"bool":@{@"bool":@"1"}
                           };
    
    NSString * desktopDir=[NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) objectAtIndex:0] ;
    NSString * thepath=[HDocumentDirectory stringByAppendingPathComponent:@"defaultSkinConfig.plist"];
    
    //写
    bool isok= [wdic writeToFile:thepath atomically:YES];
    
    if (isok) {
        debugLog(@"HDocumentDirectory:%@",HDocumentDirectory);
    }
    
    return;
    
    
    //读
    NSData *metaData = [NSData dataWithContentsOfFile:thepath]; NSError * error;
    wdic = [NSPropertyListSerialization propertyListWithData:metaData options:NSPropertyListImmutable format:NULL error:&error];
    
    if (!error) {
        NSString * ver1=[wdic valueForKeyPath:@"font.font2.fontName"];
        
        NSLog(@"ver1:%@",ver1);
        
        [wdic setValue:@"ddd" forKeyPath:@"font.font2.fontName"];
        
        [wdic writeToFile:thepath atomically:YES];
        
        
    }
    
    */
    
    
    
    
    
    
   
  
    
    /*测试font
      NSTextField * tf= [self.window.contentView viewWithTag:12];
    NSFont * font=tf.font;

    debugLog(@"fontName:%@",font.fontName);
    debugLog(@"pointSize:%f",font.pointSize);
    debugLog(@"familyName:%@",font.familyName);
    debugLog(@"displayName:%@",font.displayName);
   */
    
    
    //测试歌词解析
/*
    NSString * filepath=fileBundlePath(@"人来人往", @"krc");
    [HlyricsParser parserLRCFileWithLocalPath:filepath reqMainQueue:YES subTheadfinisHandel:^(BOOL f, NSArray * arr){}];
    
    
     return;
    */

    
    /*
    //测试自定以menu
    
    HView * hview=[[HView alloc] initWithFrame:NSMakeRect(0, 0, 400, 300)];
    
//    hview.fillBackGround=^(NSRect dirtyRect){
//        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
//        [[NSColor purpleColor] setFill];
//        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
//        
//    };
    
    
    self.menu=[[NSMenu alloc] initWithTitle:@"dsdsk"];
    
    
    
    //[self.menu setMinimumWidth:300];
        [self.menu update];
    
    
    //带方法
    NSMenuItem * mi1=[[NSMenuItem alloc] initWithTitle:@"11sadasdsadasd1" action:@selector(mi1A:) keyEquivalent:@""];
    [mi1 setState:NSOnState];
    [self.menu addItem:mi1];
    
    //无方法
    [self.menu addItemWithTitle:@"dsdsd" action:nil keyEquivalent:@""];
    
    //分割线
    HMenuItem * mi2=[[HMenuItem alloc] initWithSeperateType:YES];
    [self.menu addItem:mi2];
    
    
    //无方法
    [self.menu addItemWithTitle:@"122" action:nil keyEquivalent:@""];
    
    
    //分割线
    HMenuItem * mi3=[[HMenuItem alloc] initWithSeperateType:YES];
    [self.menu addItem:mi3];
    
    
    
    //自定义view
    NSMenuItem * mi4=[[NSMenuItem alloc] initWithTitle:@"11sadasdsadasd1" action:@selector(mi1A:) keyEquivalent:@""];;
    [mi4 setView:hview];
    [self.menu addItem:mi4];

    
    
    
    
    
   // [self.poMenuBtn addSubview:<#(NSView *)#>]
    //[self.menu setDelegate:self];

    //[self.poMenuBtn setMenu:self.menu];
    
    
    
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:30];
    [self.statusItem setMenu:self.menu];
    [self.statusItem setHighlightMode:YES];
    [self.statusItem setImage:[NSImage imageNamed:@"statusImg"]];
    //[self.statusItem setTitle:@"Glad Music"];
    [self.statusItem setAlternateImage:[NSImage imageNamed:@"statusImg"]];
    */
    
//           [HCoreConfig shareConfig];
//    
//    return;
    
    
    /*
    //实验dic 写入一个不存在的keypath
    NSMutableDictionary * rootDic=[NSMutableDictionary dictionary];
    
    
    
//    NSMutableDictionary * dic1=[NSMutableDictionary dictionary];
//    
//    [dic1 setObject:@"1" forKey:@"id"];
    
    
    NSDictionary * dic1=@{@"id":@"1"};
    
    [rootDic setObject:dic1 forKey:@"dic1"];
    
    
    debugLog(@"rootDic1:%@ \n--------",rootDic);
    
    [rootDic setValue:@"123" forKeyPath:@"dic1.id"];
    
    debugLog(@"rootDic2:%@ \n--------",rootDic);
     
     //结论:只有字典完全可变,才能写入keypath
    
    */
    
//    [HCoreConfig shareConfig];
//    [HCoreConfig testItunes];
//   return;


    
    [HCoreConfig shareConfig];
    self.mainWc=[HMainWC shareWc];
    [self.mainWc showWindow:self];


    //播放用户打开的歌曲
    [self playClickSong];
    
  
    
#ifdef DEBUG
    /*
    self.mainWc.window.title=@"悦音（测试版）";
    NSDate * date=[NSDate date];
    
    NSDate * expDate=[NSDate dateWithString:@"2014-11-30 21:24:57 +0000"];
    
    NSTimeInterval dis=[date timeIntervalSinceDate:expDate];
    
    if (dis>0) {
        exit(0);
    } else {
        
        [[HMainWC shareWc] addAutoRemoveSuccessReminderWithTitle:@"app将会在2014-11-30过期"];
    }
*/
#endif
    
}




- (void)applicationWillTerminate:(NSNotification *)notification{

    if(self.mainWc)
    [self.mainWc saveLastplayInfoSetting];
}



#pragma mark  logic


-(void)playClickSong{


    if (self.clickFilename) {
        
        HSongItem * songitem=[HSongItem tempSongItemWithPath:self.clickFilename];
        
        if (songitem) {
            //先关闭当前歌曲的boomakr
            [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
            //更改播放列表 & 更改播放面板UI
            [[HJAudioPlayer sharePlayer] configWithSongList:[NSMutableArray arrayWithObject:songitem] playSongItem:songitem];
            //要先播放,再开始更新界面,因为里面有打开bookmark的操作
            [[HJAudioPlayer sharePlayer] playSongWithSongItem:songitem];
            [[HMainWC shareWc] resetPlayplaneUIWithSongItem:songitem];
        } else {
        
            
             [HCoreConfig alertWithTitle:NSLocalizedString(@"The song is unreadable", nil) window:self.mainWc.window];
        }
        
        

        
        
    }




}


-(IBAction)quesstions:(id)sender {

    //版本更新
    NSDictionary *_infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString * currentversion = [_infoDictionary valueForKey:@"CFBundleVersion"];
    
    //subject
    NSString * subjectStr=[NSString stringWithFormat:@"suggestion about GladMusic(%@)",currentversion];
    
    NSString *mailtoAddress = [[NSString stringWithFormat:@"mailto:%@?Subject=%@&body=%@",@"cybery@126.com",subjectStr,@"i have some suggestion about GladMusic:"] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    
    
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:mailtoAddress]];
}




@end
